package com.etc.youkeshoppingssm.controller;

import com.etc.youkeshoppingssm.entity.Goods;
import com.etc.youkeshoppingssm.entity.ShoppingCart;
import com.etc.youkeshoppingssm.service.IShoppingCartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class ShoppingCartController {
    private final static Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);
    @Autowired
    private IShoppingCartService service;

    /**
     * 添加购物车
     * @param map
     * @return
     */
    @RequestMapping("/addCart")
    @ResponseBody
    public boolean addCart(@RequestBody Map map){
        logger.info("{}",map);
        int goodsId = (int) map.get("goodsId");
        int goodsCount = (int) map.get("goodsCount");
        int userId = (int) map.get("userId");
        Goods goods = new Goods();
        goods.setId(goodsId);
        ShoppingCart sc = new ShoppingCart(goods,goodsCount,userId);
        boolean flag = service.addCart(sc);
        logger.info("{}",flag);
        return flag;
    }
    @RequestMapping("/showNum/{id}")
    @ResponseBody
    public int showNum(@PathVariable("id") int userId){
        int num = service.showNum(userId);
        return num;
    }
    @RequestMapping("/details/{id}")
    @ResponseBody
    public List<ShoppingCart> findAllByUser(@PathVariable("id") int userId){
        List<ShoppingCart> list = service.findAllByUser(userId);
        return list;
    }
    @RequestMapping("/update/{cartId}/{goodsCnt}")
    @ResponseBody
    public boolean updateCart(@PathVariable("cartId") int cartId,@PathVariable("goodsCnt")int goodsCnt){
        return service.updateCart(cartId, goodsCnt);
    }
    @RequestMapping("/deleteCart/{cartId}")
    @ResponseBody
    public String deleteCart(@PathVariable("cartId")int cartId){
        boolean flag = service.deleteCart(cartId);
        logger.info("购物车删除状态{}",flag);
        if (flag){
            return "删除成功";
        }
        return "删除失败,请刷新后重新操作";
    }
}
